package edu.mis.modules.ledger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import edu.mis.model.Kmye;

public class FseSsphController extends Controller {
	public void index() {
		render("ssph.html");
	}

	/**
	 * 获得时间列表
	 */
	public void getDateList() {
		List<Kmye> data = Kmye.dao.find("SELECT date FROM kmye where isInit=1 limit 1");
		Date bdate = data.get(0).get("date"); // 科目余额表启用日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date edate = null;
		try {
			edate = sdf.parse(sdf.format(new Date())); // 当前日期
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<String> lDate = new ArrayList<String>();
		lDate.add(sdf.format(bdate));// 把开始时间加入集合
		Calendar cal = Calendar.getInstance();
		// 使用给定的 Date 设置此 Calendar 的时间
		cal.setTime(bdate);
		boolean bContinue = true;
		while (bContinue) {
			// 根据日历的规则，为给定的日历字段添加或减去指定的时间量
			cal.add(Calendar.MONTH, 1);
			// 测试此日期是否在指定日期之后
			if (edate.after(cal.getTime())) {
				lDate.add(sdf.format(cal.getTime()));
			} else {
				break;
			}
		}
		lDate.add(sdf.format(edate));// 把结束时间加入集合
		setAttr("date", lDate);
		renderJson();
	}

	/**
	 * 获取当月发生额（试算平衡）
	 */
	public void get() {
		String date = getPara("date");
		String sql = "SELECT captionId,name,sum(debitAmount),sum(creditAmount) from ( SELECT vi.*,v.date,ac.name FROM voucherItem vi LEFT JOIN voucher v ON v.voucherId=vi.voucherId LEFT JOIN account_caption ac ON ac.captionId=vi.captionId) as A WHERE date_format(date,'%Y-%m')='"
				+ date + "' group by captionId";
		List<Record> list = Db.find(sql);
		int len=list.size();
		if(len==0){
			setAttr("success", false);
			setAttr("msg", "本月未添加数据!");
			renderJson();
		}else{
			JSONArray array = new JSONArray();
			for(int i=0;i<len;i++){
				Map<String, Object> data = new HashMap<String, Object>();
				//captionId
				data.put("captionId", list.get(i).get("captionId"));
				//name
				data.put("name", list.get(i).get("name"));
				//借方发生额
				if(list.get(i).get("sum(debitAmount)")==null){
					data.put("debitAmount", 0);
				}else{
					data.put("debitAmount", list.get(i).get("sum(debitAmount)"));
				}
				//贷方发生额
				if(list.get(i).get("sum(creditAmount)")==null){
					data.put("creditAmount", 0);
				}else{
					data.put("creditAmount", list.get(i).get("sum(creditAmount)"));
				}
				array.add(i,data);
			}
			renderJson(array.toJSONString());
		}
	}
}
